<?php

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
require_once (JPATH_COMPONENT . DS . 'classes' . DS . 'fpdf' . DS . 'fpdf.php');

/**
 * Component Model
 */
class TaxiBookingModelOrder extends JModel {

    /**
     * Item data
     *
     * @var object
     */
    var $_item = null;

    /**
     * Constructor
     *
     * @since 1.0
     */
    function __construct() {
        parent::__construct();

        //$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
        $cid = JRequest::getVar('cid', 0);
        //JArrayHelper::toInteger($cid, array(0));
        $this->setId($cid);
    }

    /**
     * Method to set the identifier
     *
     * @access	public
     * @param	int item identifier
     */
    function setId($id) {
        // Set item id and wipe data
        $this->_id = $id;
        $this->_item = null;
    }

    /**
     * Method to load item data
     *
     * @access	private
     * @return	boolean	True on success
     * @since	1.0
     */
    function &getItem() {
        $query = 'SELECT *'
                . ' FROM #__taxibooking_orders'
                . ' WHERE id = ' . $this->_id
        ;
        $this->_db->setQuery($query);
        $this->_item = $this->_db->loadObject();

        return $this->_item;
    }

    /**
     * Method to store the order
     *
     * @access	public
     * @return	boolean	True on success
     * @since	1.0
     */
    function store($data) {
        // Check for request forgeries
        JRequest::checkToken() or jexit('Invalid Token');

//                global $mainframe, $option;
        $mainframe = JFactory::getApplication();
        //Get mailinformation
        $SiteName = $mainframe->getCfg('sitename');
        $MailFrom = $mainframe->getCfg('mailfrom');
        $FromName = $mainframe->getCfg('fromname');
        $tzoffset = $mainframe->getCfg('offset');
        $elsettings = & booking_helper::config();
        // get the order info
        $query = 'SELECT * FROM #__taxibooking_orders WHERE id = ' . $data['id'];
        $this->_db->setQuery($query);
        if (!$this->_db->query()) {
            $this->setError($this->_db->getErrorMsg());
            return false;
        }
        $row_queue = $this->_db->loadObject();

        // update order status
        $query = 'UPDATE #__taxibooking_orders SET
                        state="' . $_POST['state'] . '",
                        driver_id="' . $_POST['driverid'] . '",
                        datetime1="' . booking_helper::DateTime2($data['date1'], $data['time1']) . '",
                        datetime2="' . booking_helper::DateTime2($data['date2'], $data['time2']) . '"
                        WHERE id = ' . $data['id'];
        $this->_db->setQuery($query);
        if (!$this->_db->query()) {
            $this->setError($this->_db->getErrorMsg());
            return false;
        }

        // send email to owner if order status changes
        if ($row_queue->state != $_POST['state']) {
            $states = array(1 => JText::_('Accepted'),
                0 => JText::_('Rejected'),
                -1 => JText::_('Archived'),
                -2 => JText::_('Waiting'));

            $order_id = $row_queue->id;

//            $mailbody = "Hi, <br>
//                        
//                            Your Taxi booking Order Status has been changed. The status is now " . $states[$_POST['state']] . ". <br>
//                        <table border=1 width='500px'>
//                                <tr><td colspan=2 align='center'><b>DETAILS (Order No " . $order_id . ")</b></td></tr>
//                                <tr><td>Name:</td><td>" . $row_queue->names . "</td></tr>
//                                <tr><td>email:</td><td>" . $row_queue->email . "</td></tr>
//                                <tr><td>Phone:</td><td>" . $row_queue->phone . "</td></tr>
//                                <tr><td>Return trip:</td><td>" . ($row_queue->returntrip ? 'YES' : 'NO') . "</td></tr>
//                                <tr><td>Cash Price:</td><td>" . $row_queue->cprice . " GBP</td></tr>
//                                <tr><td>Passengers:</td><td>" . $row_queue->selpassengers . "</td></tr>
//                                <tr><td>Child seats:</td><td>" . $row_queue->selchildseats . "</td></tr>
//                                <tr><td>Check-in Luggage:</td><td>" . $row_queue->selluggage . "</td></tr>
//                                <tr><td>Vehicle type:</td><td>" . booking_helper::getvehicletype($row_queue->vehicletype) . "</td></tr>
//
//                                <tr><td>FROM:</td><td>" . $row_queue->begin . "</td></tr>
//                                <tr><td>" . booking_helper::AddressType($row_queue->from_dest, 1) . ":</td><td>" . $row_queue->PickupAddr1 . "</td></tr>
//                                <tr><td>" . booking_helper::AddressType($row_queue->from_dest, 2) . ":</td><td>" . $row_queue->PickupAddr2 . "</td></tr>
//                                <tr><td>" . booking_helper::AddressType($row_queue->from_dest, 3) . ":</td><td>" . $row_queue->PickupAddr3 . "</td></tr>
//                                <tr><td>Date:</td><td>" . booking_helper::DateTimeHuman($row_queue->datetime1) . "</td></tr>
//                                <tr><td>TO:</td><td>" . $row_queue->end . "</td></tr>
//                                <tr><td>" . booking_helper::AddressType($row_queue->to_dest, 1) . ":</td><td>" . $row_queue->PickupAddr4 . "</td></tr>
//                                <tr><td>" . booking_helper::AddressType($row_queue->to_dest, 2) . ":</td><td>" . $row_queue->PickupAddr5 . "</td></tr>
//                                <tr><td>" . booking_helper::AddressType($row_queue->to_dest, 3) . ":</td><td>" . $row_queue->PickupAddr6 . "</td></tr>
//                                " . ($row_queue->returntrip ? "<tr><td>Date for your return trip:</td><td>" . booking_helper::DateTimeHuman($row_queue->datetime2) . "</td></tr>" : "") . "
//                                <tr><td>Message:</td><td>&nbsp;" . $row_queue->message . "</td></tr>
//                                <tr><td>Contact us:</td><td>" . booking_helper::phone() . "</td></tr>
//                        </table>";
//                        
//fopen("/components/com_taxibooking/documents/{$order_id}.pdf")
            /**
             * New mail interface
             */
            $order_status = '';

            if ($_POST['state'] == '1') {
                $order_status .= '<span style="color:green;">ACCEPTED</span>';
            } elseif ($_POST['state'] == '0') {
                $order_status .= '<span style="color:red;">REJECTED</span>';
            } elseif ($_POST['state'] == '-1') {
                $order_status .= '<span style="color:yellow;">ARCHIVED</span>';
            } elseif ($_POST['state'] == '-2') {
                $order_status .= '<span style="color:green;">WAITING</span>';
            }

            $mailbody = '<table border="0">';
            $mailbody .= '<tr><td align="right"><img src="' . JURI::root() . 'images/stories/taxibooking/' . $elsettings->header_logo . '" alt="header_logo" border="0" /></td></tr>';
            $mailbody .= '<tr><td>&nbsp;</td></tr>';
            $mailbody .= '<tr><td align="left">' . $elsettings->header_info . '</td></tr>';
            $mailbody .= '<tr><td>&nbsp;</td></tr>';
            $mailbody .= '<tr><td><hr></td></tr>';
            $mailbody .= '<tr>
                            <td>
                                <table border="0" width="100%">
                                    <tr width="100%">
                                        <td width="50%">ORDER NO:&nbsp;&nbsp;&nbsp;' . str_pad($row_queue->id, 5, "0", STR_PAD_LEFT) . '</td>
                                        <td width="50%">
                                            ORDER STATUS:&nbsp;&nbsp;&nbsp;' . $order_status . '
                                        </td>
                                     </tr>
                                    <tr><td colspan="2"><hr></td></tr>

                                    <tr width="100%">
                                        <td width="50%" style="vertical-align:top;">
                                            <span style="text-decoration:underline;">Traveller information</span>
                                            <table border="0" width="100%">
                                                <tr width="100%">
                                                    <td width="30%">Passenger:</td>
                                                    <td width="70%">' . $row_queue->names . '</td>
                                                 </tr>
                                                 <tr width="100%">
                                                    <td width="30%">Email:</td>
                                                    <td width="70%">' . $row_queue->email . '</td>
                                                 </tr>
                                                 <tr width="100%">
                                                    <td width="30%">Phone:</td>
                                                    <td width="70%">' . $row_queue->phone . '</td>
                                                 </tr>
                                             </table>
                                        </td>
                                        <td width="50%" style="vertical-align:top;">
                                            <span style="text-decoration:underline;">Carrier Details</span>
                                            <table border="0" width="100%">';

            if ($row_queue->selpassengers > 0) {
                $mailbody .= '<tr width="100%">
                                                    <td width="45%">Passengers:</td>
                                                    <td width="55%">' . $row_queue->selpassengers . '</td>
                                                 </tr>';
            }
            if ($row_queue->selinfantseats > 0) {
                $mailbody .= '<tr width="100%">
                                                    <td width="45%">Infant seats:</td>
                                                    <td width="55%">' . $row_queue->selinfantseats . '</td>
                                                 </tr>';
            }
            if ($row_queue->selchildseats > 0) {
                $mailbody .= '<tr width="100%">
                                                    <td width="45%">Child seats:</td>
                                                    <td width="55%">' . $row_queue->selchildseats . '</td>
                                                 </tr>';
            }
            if ($row_queue->selboosterseats > 0) {
                $mailbody .= '<tr width="100%">
                                                    <td width="45%">Booster seats:</td>
                                                    <td width="55%">' . $row_queue->selboosterseats . '</td>
                                                 </tr>';
            }
            if ($row_queue->selluggage > 0) {
                $mailbody .= '<tr width="100%">
                                                    <td width="45%">Check-in Luggage:</td>
                                                    <td width="55%">' . $row_queue->selluggage . '</td>
                                                 </tr>';
            }

            $mailbody .= '     <tr width="100%">
                                                    <td width="45%">Vehicle type:</td>
                                                    <td width="55%">' . booking_helper::getvehicletype($row_queue->vehicletype) . '</td>
                                                 </tr>
                                            </table>
                                        </td>
                                     </tr>

                                     <tr><td colspan="2"><hr></td></tr>

                                    <tr width="100%">
                                        <td width="50%" style="vertical-align:top;">
                                            <span style="text-decoration:underline;">Pick-up Information</span>
                                            <table border="0" width="100%">
                                                <tr width="100%">
                                                    <td width="30%">Driver Name:</td>
                                                    <td width="70%">' . $row_queue->driver_id . '</td>
                                                 </tr>
                                                <tr width="100%">
                                                    <td width="30%">FROM:</td>
                                                    <td width="70%">' . $row_queue->begin . '</td>
                                                 </tr>
                                                 <tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->from_dest, 1) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr1 . '</td>
                                                 </tr>';

            if ($row_queue->from_dest == 1) {
                $mailbody .= '<tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->from_dest, 2) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr2 . '</td>
                                                </tr>
                                                <tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->from_dest, 3) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr3 . '</td>
                                                </tr>';
            }

            $mailbody .= '<tr width="100%">
                                                <td width="30%">Date:</td>
                                                <td width="70%">' . booking_helper::DateTimeHuman($row_queue->datetime1) . '</td>
                                               </tr>';
            $mailbody .= '</table>
                                        </td>
                                        <td width="50%" style="vertical-align:top;">
                                            <span style="text-decoration:underline;">Drop-off Information</span>
                                            <table border="0" width="100%">
                                                <tr width="100%">
                                                    <td width="30%">TO:</td>
                                                    <td width="70%">' . $row_queue->end . '</td>
                                                 </tr>
                                                 <tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->to_dest, 1) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr4 . '</td>
                                                 </tr>';

            if ($row_queue->to_dest == 1) {
                $mailbody .= '<tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->to_dest, 2) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr6 . '</td>
                                                </tr>
                                                <tr width="100%">
                                                    <td width="30%">' . booking_helper::AddressType($row_queue->to_dest, 3) . ':</td>
                                                    <td width="70%">' . $row_queue->PickupAddr6 . '</td>
                                                </tr>';
            }
            $mailbody .= '</table>
                                        </td>
                                     </tr>
                                  </table>
                               </td>
                             </tr>
                             <tr><td><hr></td></tr>';

            $mailbody .= ( $row_queue->returntrip) ? '<tr><td>Date for your return trip:&nbsp;&nbsp;&nbsp;' . booking_helper::DateTimeHuman($row_queue->datetime2) . '</td></tr><tr><td><hr></td></tr>' : '';

            $mailbody .= ( $row_queue->message != '') ? '<tr><td>Message:&nbsp;&nbsp;&nbsp;' . $row_queue->message . '</td></tr><tr><td><hr></td></tr>' : '';
            $mailbody .= '
                                     <tr>
                                        <td>
                                        <strong>
                                        Cost:&nbsp;&nbsp;' . $elsettings->currency_symbol . $row_queue->cprice . '
                                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                        Payment Method:&nbsp;&nbsp;' . strtoupper($row_queue->payment) . ' </strong>
                                        </td>
                                     </tr>
                                     <tr><td><hr></td></tr>

                                     <tr><td><center><b>Thank You & Have A Pleasant Journey.</b></center></td></tr>
                                     <tr>
                                        <td>
                                            <center>
                                            <span style="color:blue">Orders are subject to our terms & conditions. We welcome all comments on the services we provide.</span>
                                            </center>
                                        </td>
                                      </tr>
                                      <tr><td><hr></td></tr>
                                      <tr><td><center>Contact us:' . $elsettings->contact_info . '</center></td></tr>
                                </table>
                            </td>
                           </tr>';
            $mailbody .= '</table>';
            /**
             * Creating a pdf file
             */
            if ($_POST['state'] == '1') {// Accepted state should be 1

                $app = JFactory::getApplication();

                $config = new JConfig();
                $site_name = $app->getCfg('sitename');
                $imageUrl = JPATH_ROOT . '/images/stories/taxibooking/' . $elsettings->header_logo;

                $pdf = new FPDF('P', 'mm', 'A4');
                $pdf->AddPage();
                $pdf->SetMargins(10, 20);
                $pdf->SetDrawColor(200, 200, 200);
                $pdf->SetFillColor(240, 240, 240);
                $pdf->SetTextColor(150, 150, 150);
                // Thickness of frame (1 mm)


                $pdf->SetLineWidth(1);
                $pdf->SetFont('Arial', 'B', 16);
                if (file_exists($imageUrl) && trim($elsettings->header_logo) != '')
                    $pdf->Image($imageUrl, 162, 6, 30, 30);
                $pdf->Ln();
                $pdf->Cell(150, 10, $site_name, 0, 0, 'C', true);

                $pdf->Ln();

                $pdf->SetTextColor(50, 50, 50);
                $pdf->SetFont('Arial', 'I', 14);
                $pdf->Cell(150, 10, ' INVOICE ', 0, 0, 'C', true);
                $pdf->Ln();
                $pdf->SetFont('Arial', '', 12);
                $pdf->Cell(40, 9, "Your Taxi booking Order has been invoiced. ");
                $pdf->Ln();
                $pdf->SetFont('Arial', 'B', 11);
                $pdf->Cell(120, 10, "Order No " . $order_id);
                $pdf->SetFont('Arial', '', 11);
                $pdf->Cell(40, 10, " Status: ");
                $pdf->SetFont('Arial', 'B', 11);
                if (strtolower(trim($_POST['state'])) == 'accepted')
                    $this->SetTextColor(0, 50, 0);
                $pdf->Cell(40, 10, $states[$_POST['state']]);
                if (strtolower($_POST['state']) == 'accepted')
                    $this->SetTextColor(50, 50, 50);
                // Printing Customer Details



                $pdf->Ln();
                $pdf->SetFont('Arial', '', 10);
                $pdf->SetFont('Arial', 'U', 10);
                $pdf->Cell(180, 6, 'Traveller Information', 0, 0, 'L', true);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Ln();
                $pdf->Cell(130, 10, "Passenger Name: " . $row_queue->names);
                $pdf->Cell(40, 10, "Email: " . $row_queue->email);
                $pdf->Ln();
                $pdf->Cell(130, 10, "Phone: " . $row_queue->phone);
                $pdf->Ln();

                $pdf->SetFont('Arial', 'U', 10);
                $pdf->Cell(180, 6, 'Carrier Details', 0, 0, 'L', true);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Ln();
                $pdf->Cell(130, 10, "Passengers: " . $row_queue->selpassengers);
                $pdf->Cell(40, 10, " Vehicle Type: " . booking_helper::getvehicletype($row_queue->vehicletype));
                $pdf->Ln();
                $pdf->Cell(130, 10, "Check-in Luggage: " . $row_queue->selluggage);
                $pdf->Cell(40, 10, "Child Seats: " . $row_queue->selchildseats);
                $pdf->Ln();

                $pdf->SetFont('Arial', 'U', 10);
                $pdf->Cell(180, 6, 'Pick-up Information', 0, 0, 'L', true);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Ln();
                $pdf->Cell(130, 10, "From Location: " . $row_queue->begin);
                $pdf->Cell(40, 10, "Driver: " . $row_queue->driver_id);
                $pdf->Ln();
                $pdf->Cell(130, 10, "Date: " . booking_helper::DateTimeHuman($row_queue->datetime1));
                if ($row_queue->returntrip)
                    $pdf->Cell(40, 10, "Return Date: " . booking_helper::DateTimeHuman($row_queue->datetime2));
                $pdf->Ln();


                $pdf->SetFont('Arial', 'U', 10);
                $pdf->Cell(180, 6, 'Drop-off Information', 0, 0, 'L', true);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Ln();
                $pdf->Cell(130, 8, "To Location: " . $row_queue->end);
                $pdf->Ln();

                $pdf->SetFont('Arial', 'U', 10);
                $pdf->Cell(180, 6, 'Payment Details', 0, 0, 'L', true);
                $pdf->SetFont('Arial', '', 10);
                $pdf->Ln();
//
                $pdf->Cell(130, 10, "Return Trip: " . ($row_queue->returntrip ? 'YES' : 'NO'));
                $pdf->Cell(40, 10, "Cash Price: " . html_entity_decode($elsettings->currency_symbol) . "" . $row_queue->cprice);


                $pdf->Ln();
                $pdf->Ln();
                $pdf->Cell(180, 7, "Contact us: " . strip_tags($elsettings->contact_info), 0, 0, 'C', true);

                $pdf_file = JPATH_COMPONENT . DS . 'documents' . DS . $order_id . '.pdf';
                $pdf->Output($pdf_file, 'F');
            }

            $mail = & JFactory::getMailer();

            $mail->setSender(array($MailFrom, $FromName));
            $mail->setSubject('Taxi booking Status has been changed. Order Id - ' . $order_id);
            $mail->setBody($mailbody);
            $mail->addAttachment($pdf_file);
            $mail->IsHTML(true);

            $mail->addRecipient($row_queue->email);

            $sent = $mail->Send();
        }

        return true;
    }

}

?>